package com.banciyuan.bcywebview.biz.post;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.api.IllustApi;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.groupdetail.AddGroupActivity;
import com.banciyuan.bcywebview.biz.post.cos.CosPostActivity;
import com.banciyuan.bcywebview.biz.post.illust.illustPostActivity;
import com.banciyuan.bcywebview.biz.post.rule.RuleHelper;
import com.banciyuan.bcywebview.biz.post.rule.SimpleRuleImpl;
import com.banciyuan.bcywebview.biz.post.write.PostWriteDialog;
import com.banciyuan.bcywebview.biz.post.write.WriteArticleActivity;
import com.banciyuan.bcywebview.biz.post.write.series.SelectSeriesActivity;
import com.banciyuan.bcywebview.biz.write.write.WriteActivity;
import com.banciyuan.bcywebview.utils.file.ImageManager;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import de.greenrobot.daoexample.model.PostRule;
import de.greenrobot.daoexample.model.Rules;

/**
 * Created by squall on 2015/12/29.
 */
public class StartPostActivity extends BaseActivity implements View.OnClickListener {

    public static final int GO_WRITEARTICLE = 100;
    public static final int GO_SERIES = 101;
    private ImageView bg_img;
    private TextView post_title;
    private LinearLayout ll_draw;
    private LinearLayout ll_write;
    private LinearLayout ll_cos;
    private ImageView iv_draw;
    private ImageView iv_write;
    private ImageView iv_cos;
    private ImageView iv_new;
    private ImageView iv_topic;

    private View viewLoading;
    private String type = "main";
    private String work = "";
    private String tag = "";

    private PostRule postRule;
    private RulesDialog rulesDialog;
    private PostWriteDialog postWriteDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initArgs();
        setContentView(R.layout.post_circle_start_activity);
        initUi();
        initAction();
    }


    @Override
    protected void initArgs() {
        type = getIntent().getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        work = getIntent().getStringExtra(gotoUtil.INTENT_VALUE_TWO);
        tag = getIntent().getStringExtra(gotoUtil.INTENT_VALUE_THREE);
    }

    @Override
    protected void initUi() {
        bg_img = (ImageView) findViewById(R.id.start_back);
        ll_draw = (LinearLayout) findViewById(R.id.draw_click);
        ll_write = (LinearLayout) findViewById(R.id.write_click);
        ll_cos = (LinearLayout) findViewById(R.id.cos_click);
        iv_draw = (ImageView) findViewById(R.id.draw_pic);
        iv_write = (ImageView) findViewById(R.id.write_pic);
        iv_cos = (ImageView) findViewById(R.id.cos_pic);
        iv_new = (ImageView) findViewById(R.id.new_pic);
        iv_topic = (ImageView) findViewById(R.id.topic_pic);
        viewLoading = findViewById(R.id.pb_loading);
        post_title = (TextView) findViewById(R.id.post_title);
        try {
            bg_img.setImageBitmap(BitmapFactory.decodeFile(ImageManager.getTemp(this) + "/screenshot.jpg"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (type.equals("circle")) {
            post_title.setText(getString(R.string.share_to_friend));
        } else {
            post_title.setText(getString(R.string.mine_post));
        }
    }

    @Override
    protected void initAction() {
        iv_draw.setOnClickListener(this);
        iv_cos.setOnClickListener(this);
        iv_new.setOnClickListener(this);
        iv_write.setOnClickListener(this);
        iv_topic.setOnClickListener(this);
        findViewById(R.id.post_cancle).setOnClickListener(this);
        findViewById(R.id.post_parent).setOnClickListener(this);
    }

    @Override
    public void onBackPressed() {
        finish();
        overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
    }

    @Override
    public void onClick(View v) {
        if (judgeLogin()) {
            switch (v.getId()) {
                case R.id.draw_pic:
                    judge(IllustApi.getVerifydrawer());
                    break;
                case R.id.cos_pic:
                    judge(CoserApi.getVerifycoser());
                    break;
                case R.id.write_pic:
                    judge(NovelApi.getVerifywriter());
                    break;
                case R.id.new_pic:
                    Intent intent = new Intent(this, WriteActivity.class);
                    intent.putExtra("work", work);
                    if (!type.equals("channal")) {
                        intent.putExtra("tag", tag);
                    }
                    startActivity(intent);
                    finish();
                    break;
                case R.id.post_parent:
                case R.id.post_cancle:
                    finish();
                    overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
                    break;
                case R.id.topic_pic:
                    gotoUtil.gotoAct(this, AddGroupActivity.class, "", work, tag);
                    finish();
                    break;
            }
        }
    }

    private void processData(String options) {
        viewLoading.setVisibility(View.GONE);
        if (CoserApi.getVerifycoser().equals(options))
            if (postRule.is_coser()) {
                postCos();
            } else {
                showRulesDialog(postRule.getRules(), CoserApi.getBecoser());
            }
        if (IllustApi.getVerifydrawer().equals(options))
            if (postRule.is_drawer()) {
                postDraw();
            } else {
                showRulesDialog(postRule.getRules(), IllustApi.getBedrawer());
            }
        if (NovelApi.getVerifywriter().equals(options))
            if (postRule.is_writer()) {
                postWrite();
            } else {
                showRulesDialog(postRule.getRules(), NovelApi.getBewriter());
            }
    }

    private void postCos() {
        if (!type.equals("channal")) {
            gotoUtil.gotoAct(this, CosPostActivity.class, tag, work);
        } else {
            gotoUtil.gotoAct(this, CosPostActivity.class, "", work);
        }

        finish();
    }

    private void postDraw() {
        if (!type.equals("channal")) {
            gotoUtil.gotoAct(this, illustPostActivity.class, tag, work);
        } else {
            gotoUtil.gotoAct(this, illustPostActivity.class, "", work);
        }
        finish();
    }

    private void postWrite() {
        showPostWriteDialog();
    }

    private void showPostWriteDialog() {
        PostWriteDialog.Builder builder = new PostWriteDialog.Builder(this);
        builder.setSingleWorkButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(StartPostActivity.this, WriteArticleActivity.class);
                if (!type.equals("channal")) {
                    intent.putExtra("tags", tag);
                }
                intent.putExtra(gotoUtil.INTENT_VALUE_FOUR, work);
                startActivityForResult(intent, GO_WRITEARTICLE);
            }
        });
        builder.setSerialWorkButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(StartPostActivity.this, SelectSeriesActivity.class);
                if (!type.equals("channal")) {
                    intent.putExtra("tags", tag);
                }
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, work);
                startActivityForResult(intent, GO_SERIES);
            }
        });

        postWriteDialog = builder.create();
        if (!isFinishing())
            postWriteDialog.show();
    }

    private void showRulesDialog(Rules rules, final String option) {
        RulesDialog.Builder builder = new RulesDialog.Builder(this, rules);
        rulesDialog = builder.setConfirmButton(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                verify(option);
            }
        }).create();
        if (!isFinishing())
            rulesDialog.show();
    }

    private void judge(final String options) {
        viewLoading.setVisibility(View.VISIBLE);
        RuleHelper ruleHelper = new RuleHelper(StartPostActivity.this, new SimpleRuleImpl() {
            @Override
            public void judgeTrue(JSONObject result) {
                try {
                    JSONObject jsonObject = result.getJSONObject(HttpUtils.UPLOAD_DATA);
                    Gson gson = new Gson();
                    postRule = gson.fromJson(jsonObject.toString(), PostRule.class);
                    processData(options);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void judgeFalse(JSONObject result) {
                try {
                    String data = result.getString(HttpUtils.UPLOAD_DATA);
                    MyToast.show(StartPostActivity.this, data.toString(), Toast.LENGTH_SHORT);
                    viewLoading.setVisibility(View.GONE);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        ruleHelper.judge(options);
    }

    private void verify(final String options) {

        RuleHelper ruleHelper = new RuleHelper(StartPostActivity.this, new SimpleRuleImpl() {
            @Override
            public void changeSucc(JSONObject result) {
                if (null != rulesDialog && rulesDialog.isShowing())
                    rulesDialog.dismiss();
                if (CoserApi.getBecoser().equals(options))
                    postCos();
                if (IllustApi.getBedrawer().equals(options))
                    postDraw();
                if (NovelApi.getBewriter().equals(options))
                    postWrite();
            }

            @Override
            public void changeFail(JSONObject result) {
                try {
                    String data = result.getString(HttpUtils.UPLOAD_DATA);
                    MyToast.show(StartPostActivity.this, data.toString(), Toast.LENGTH_SHORT);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        ruleHelper.verify(options);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == GO_SERIES || requestCode == GO_WRITEARTICLE) && resultCode == RESULT_OK) {
            if (null != rulesDialog && rulesDialog.isShowing())
                rulesDialog.dismiss();
            if (null != postWriteDialog && postWriteDialog.isShowing())
                postWriteDialog.dismiss();
            finish();
        }
    }

    private boolean judgeLogin() {
        if (!UserDataHelper.ifLogin(this) || TextUtils.isEmpty(UserDataHelper.getInstance(this).getToken())) {
            MyToast.show(this, getString(R.string.loginfirst));
            finish();
            overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
            return false;
        } else {
            return true;
        }
    }
}
